package com.kasax.plugin.shadow

import com.android.build.gradle.BaseExtension
import com.kasax.plugin.shadow.transform.TestTransform
import com.kasax.plugin.shadow.utils.LogUtils
import com.kezong.fataar.RClassesTransform
import org.gradle.api.Plugin
import org.gradle.api.Project

class TestALibraryPlugin implements Plugin<Project> {
    private static final String LOG_TAG = "TestPlugin"

    void apply(Project project) {
        LogUtils.d(LOG_TAG, "apply")

        // 注册扩展
        project.extensions.create("shadowExt", ShadowExtenstion)
        // 注册 CustomLogTransform
        def android = project.extensions.getByType(BaseExtension)
        // 获取扩展
        def shadowExts = project["shadowExt"]
        // 注册插桩
        android.registerTransform(new TestTransform(shadowExts))
        LogUtils.d(LOG_TAG, "use in other module")

        project.afterEvaluate {
            // 遍历 Library 的每个变体
            android.libraryVariants.all { variant ->
                // 1) 先拿到你关心的“目标任务”：RClassesTransform 为该变体生成的实例
//                def rClassesTransform = project.tasks.getByName("com.kezong.fataar.RClassesTransform")
                def rClassesTransform = project.tasks.withType(RClassesTransform)
                        .find { it.variantName == variant.name }

                // 2) 再拿到你要排序的自定义 Transform 任务（按命名规则匹配）
                def targetName = "transformClassesWith${TestTransform.class.simpleName.replace('Transform', '')}For${variant.name.capitalize()}"
                def myTask = project.tasks.findByName(targetName)

                if (rClassesTransform && myTask) {
                    myTask.mustRunAfter rClassesTransform
                    LogUtils.d(LOG_TAG, "Ordered: ${myTask.name} mustRunAfter ${rClassesTransform.name} [${variant.name}]")
                } else {
                    LogUtils.d(LOG_TAG, "Missing task - RClassesTransform: ${rClassesTransform?.name ?: 'N/A'}, MyTransform: ${myTask?.name ?: 'N/A'}} [${variant.name}]")
                }
            }
        }
    }
}